package com.itheima.config;

import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.*;
import java.util.EnumSet;

public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * 初始化父容器资源
     * @return
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[0];
    }

    /**
     * 为方法提供spring的核心配置类，底层自动初始化IOC容器 子容器
     * @return
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringMvcConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    //乱码处理 TODO
//    @Override
//    protected Filter[] getServletFilters() {
//        CharacterEncodingFilter filter = new CharacterEncodingFilter();
//        //强迫进行编码
//        filter.setForceEncoding(true);
//        filter.setEncoding("UTF-8");
//        //强迫响应时数据转换
//        filter.setForceResponseEncoding(true);
//        return new Filter[]{filter};
//    }


//    @Override
//    public void onStartup(ServletContext servletContext) throws ServletException {
//        //调用父类的onStartup方法，底层构建核心调取器，并初始化父子容器
//        super.onStartup(servletContext);
//        FilterRegistration.Dynamic dynamic = servletContext.addFilter("characterEncodingFilter", CharacterEncodingFilter.class);
//        //设置过滤器初始化的参数
//        dynamic.setInitParameter("encoding","utf-8");
//        dynamic.setInitParameter("forceRequestEncoding","true");
//        dynamic.setInitParameter("forceResponseEncoding","true");
//        //设置过滤器的过滤规则 isMatchAfter: true，在其他过滤器执行之后进行过滤，fase: 优先执行
//        EnumSet<DispatcherType> async = EnumSet.of(DispatcherType.ASYNC, DispatcherType.REQUEST, DispatcherType.FORWARD);
//        dynamic.addMappingForUrlPatterns(async,true,"/*");
//    }
}
